package com.dangdang.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.dangdang.domain.Category;
import com.dangdang.util.HbnUtil;

/**
 * 
 * @author Wangpeihu
 * @since 28/12/2009
 */
public class CategoryDao {

	/**
	 * @InsertCategory
	 * @param product
	 */
	public void InsertCategory(Category category) {
		Session s = HbnUtil.getSession();
		try {
			s.beginTransaction();
			s.save(category);
			s.getTransaction().commit();
		} catch (HibernateException e) {
			s.getTransaction().rollback();
			e.printStackTrace();
		}
		s.close();
	}

	/**
	 * @Get category
	 * @return list
	 */
	@SuppressWarnings("unchecked")
	public List<Category> getCategory() {
		Session s = HbnUtil.getSession();
		List<Category> categoryList = null;
		List<Category> categoryListOk = new ArrayList<Category>();
		Query query = s.createQuery("from Category");
		categoryList = query.list();
		for (Category category : categoryList) {
			if (category.getLevel() == 2) {
				category.setName("&nbsp&nbsp;" + category.getName());
				categoryListOk.add(category);
			} else {
				categoryListOk.add(category);
			}
		}
		return categoryListOk;
	}

	/**
	 * @update a Book
	 * @param Book
	 */
	public void updateCategory(Category category) {
		Session s = HbnUtil.getSession();
		try {
			s.beginTransaction();
			s.update(category);
			s.getTransaction().commit();
		} catch (HibernateException e) {
			s.getTransaction().rollback();
		}
	}

}
